/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.product.service.aaa
   Module Description   :

   Date Created      : 2010/5/13
   Original Author   : feeling
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.product.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.FileUtils;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.SpringCommonTest;
import com.yaodian100.ec.channel.entity.ChannelTemplate;
import com.yaodian100.ec.channel.service.ChannelService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.remote.RemoteProductService;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;

/**
 * @author feeling
 * 
 */
public class aaa extends SpringCommonTest {
	private static ProductService productService;
	// private static GenerateService generateService;
	// private static CategoryService categoryService;
	private static ChannelService channelService;
	private static DaphneProductService daphneProductService;
	private static TimeLimitSaleService timeLimitSaleService;
	private static RemoteProductService remoteProductService;
	private static BaseManager baseManager;
	private static JdbcTemplate jdbcTemplate;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			configCtx();
			productService = ctx.getBean(ProductService.class);
			// generateService = ctx.getBean(GenerateService.class);
			// categoryService = ctx.getBean(CategoryService.class);
			channelService = ctx.getBean(ChannelService.class);
			daphneProductService = ctx.getBean(DaphneProductService.class);
			timeLimitSaleService = ctx.getBean(TimeLimitSaleService.class);
			remoteProductService = ctx.getBean(RemoteProductService.class);
			baseManager = ctx.getBean(BaseManager.class);
			jdbcTemplate = ctx.getBean(JdbcTemplate.class);
			Properties props = new java.util.Properties();
			props.load((new URL("http://feeling-nb.yaodian100.com/static/server/.server.prop")).openStream());
			System.out.println("props = " + props);
			ServerValue.setMidApachePath(props.getProperty("midApachePath"));
			ServerValue.setFrontApachePath(props.getProperty("frontApachePath"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void productCategoryTest() {
		Object[] objs = baseManager.queryByHql("from ProductCategory where categoryId = ? and productId = ? ",
				new Object[] { "1824", "00013649" });
		System.out.println(ArrayUtils.isEmpty(objs));

	}

	@Test
	public void createDaphneProduct() throws IOException, InvalidFormatException {
		// String[] productId = new String[] { "00015011", "00015015", "00015016", "00015017", "00015018", "00015019",
		// "00003745", "00003740", "00003738", "00003736", "00003659", "00003722", "00003514", "00003380", "00013756",
		// "00013757", "00013758", "00013759", "00028973", "00027162", "00027233", "00027170", "00027864" };
		File file = new File("D:/yaodian100.com/sit_table_export.xls");
		InputStream inp = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);
		Cell cell = null;
		DecimalFormat df = new DecimalFormat("00000000");
		List<String> stringList = new ArrayList<String>();
		for (int i = 0; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			cell = row.getCell(0);
			// logger.info("cell:{}", row.getCell(0));
			stringList.add(df.format(Long.valueOf(cell.getStringCellValue()).longValue()));
		}

		String[] productIds = stringList.toArray(new String[0]);

		daphneProductService.importDaphneProduct(org.apache.commons.httpclient.util.DateUtil.formatDate(new Date(),
				"yyyyMMdd"), productIds);
		// daphneProductService.getAvailableDaphneProductMap();
	}

	/**
	 * 商品屬性
	 */
	@Test
	public void createProductAttribute() {
		List<Object> pds = productService.getProductCategoryByCategoryId(Long.parseLong("856"), "");
		for (Object pd : pds) {
			logger.info("pd:{}", pd);
			Object[] pdArray = (Object[]) pd;
			for (Object pda : pdArray) {
				logger.info("pda:{}", pda);
			}

		}

	}

	@Test
	public void test22() {

		Date date = new Date(1282533371);
		DateFormat dataformat = DateFormat.getDateInstance(DateFormat.LONG);
		String s4 = dataformat.format(date);
		System.out.println(dataformat.format(date));
	}

	@Test
	public void testChannelTemplate() {
		ChannelTemplate template = channelService.getAvailableChannelTemplate("adwaysps", "CPS");
		logger.info("template:{}", template);
	}

	// @Test
	// public void testGenerateCateMainGold() throws CoreException, Exception {
	// generateService.generateCateMainGoldAdv("20100715101010");
	// }
	//
	// @Test
	// public void testGenerateIdxGoldFour() throws CoreException, Exception {
	// generateService.generateIdxGoldFourV2(null);
	// }
	//
	// @Test
	// public void testGenerateIdxHotSale() throws CoreException, Exception {
	// generateService.generateIdxHotSaleV2("20100623101010");
	// }
	//
	// @Test
	// public void testGenerateIdxMainGoldAdv() throws CoreException {
	// generateService.generateIdxMainGoldAdv("20100301000000");
	// }
	//
	// @Test
	// public void testGenerateIdxMainGoldAdv_V2() throws CoreException {
	// generateService.generateIdxMainGoldAdv_V2("20100301000000");
	// }

	// @Test
	// public void testGenerateTab3() throws CoreException {
	// // generateService.generateTab3(categoryService.get(66l));
	// // build all cateogry
	// CommonCriteria criteria = new CommonCriteria();
	// criteria.addEq("level", "0");
	// List<Category> categories = categoryService.getList(0, -1, criteria, null);
	// for (Category category : categories) {
	// generateService.generateTab3(category);
	// }
	// }

	// @Test
	// public void testGenerateIdxMidBoxAdv() throws CoreException {
	// generateService.generateIdxMidBoxAdv("20100301000000");
	// }
	//
	// @Test
	// public void testGenerateIdxMidBoxAdv_V2() throws CoreException {
	// generateService.generateIdxMidBoxAdv_V2("20100301000000");
	// }
	//
	// @Test
	// public void testGenerateIdxNews() throws CoreException, Exception {
	// generateService.generateIdxNews(null);
	// }
	//
	// @Test
	// public void testGenerateMainCateMainGoldAdv() throws CoreException {
	// generateService.generateMainCateMainGoldAdv("20100301000000");
	// }
	//
	// @Test
	// public void testGenerateRightDownAdv() throws CoreException, Exception {
	// generateService.generateRightDownAdv(Long.parseLong("0"), "TOP");
	// generateService.generateRightDownAdv(Long.parseLong("0"), "BTM");
	// }
	//
	// @Test
	// public void testGenerateRightDownAdv2() throws CoreException, Exception {
	// generateService.generateRightDownAdvV2(Long.parseLong("0"), "TOP");
	// generateService.generateRightDownAdvV2(Long.parseLong("0"), "BTM");
	// }
	//
	// @Test
	// public void testGenerateSideBar() throws CoreException {
	// generateService.generateSideBarMenu2("20100301000000");
	// }
	//
	// @Test
	// public void testGenerateTab3() throws CoreException {
	// // generateService.generateTab3(categoryService.get(66l));
	// // build all cateogry
	// // CommonCriteria criteria = new CommonCriteria();
	// // criteria.addEq("level", "0");
	// // List<Category> categories = categoryService.getList(0, -1, criteria, null);
	// // for (Category category : categories) {
	// // generateService.generateTab3(category);
	// // }
	// generateService.generateIndexTab3V2("20100615160000");
	// }

	// @Test
	// public void updateProductMainCategoryId() throws CoreException, InvalidFormatException, IOException {
	// File file = new File("D:/yaodian100.com/update_product_maincategoryid.xls");
	// InputStream inp = new FileInputStream(file);
	// Workbook wb = WorkbookFactory.create(inp);
	// Sheet sheet = wb.getSheetAt(0);
	// Cell oldcell = null;
	// Cell newcell = null;
	// CommonCriteria criteria = null;
	// List<Product> oldProducts = null;
	// List<ProductCategory> productCategories = null;
	// Category category = null;
	// for (int i = 0; i <= sheet.getLastRowNum(); i++) {
	// Row row = sheet.getRow(i);
	// oldcell = row.getCell(2);
	// newcell = row.getCell(1);
	// criteria = new CommonCriteria();
	// // System.out.println(oldcell.getNumericCellValue());
	// // System.out.println(Double.valueOf(oldcell.getNumericCellValue()).intValue());
	// criteria.addEq("mainCategoryID", Double.valueOf(oldcell.getNumericCellValue()).intValue());
	// oldProducts = productService.getList(0, -1, criteria, null);
	// for (Product product : oldProducts) {
	// product.setMainCategoryID(Double.valueOf(newcell.getNumericCellValue()).intValue());
	// ProductCategory pc = new ProductCategory();
	// category = categoryService.get(Long.parseLong(String.valueOf(Double.valueOf(newcell.getNumericCellValue())
	// .intValue())));
	// productCategories = new ArrayList<ProductCategory>();
	// pc.setCategoryId(category.getId());
	// pc.setCategoryName(category.getName());
	// pc.setCategoryPath(category.getCategoryPath());
	// pc.setShowSeq(101);
	// pc.setProductId(product.getProductId());
	// productCategories.add(pc);
	// productService.saveOrUpdateProductCategoryBatch(product, productCategories);
	//
	// }
	// }
	// }

	// 主分类搬家
	@Test
	public void updateProductMainCategoryIdBatch() throws CoreException, InvalidFormatException, IOException {
		File file = new File("D:/yaodian100.com/女裝批次修改主分類.xlsx");
		InputStream inp = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);
		Cell oldcell = null;
		Cell newcell = null;
		CommonCriteria criteria = null;
		List<Product> oldProducts = null;
		StringBuffer sb = new StringBuffer();
		boolean result = false;
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			oldcell = row.getCell(0);
			newcell = row.getCell(1);
			sb.append("start old = ").append(row.getCell(0)).append(",new = ").append(newcell).append("\n");
			criteria = new CommonCriteria();
			criteria.addEq("mainCategoryID", Double.valueOf(oldcell.getNumericCellValue()).intValue());
			oldProducts = productService.getList(0, -1, criteria, null);
			result = productService.saveOrUpdateMainProductCategoryBatch(oldProducts, String.valueOf(Double.valueOf(
					oldcell.getNumericCellValue()).intValue()), String.valueOf(Double.valueOf(newcell.getNumericCellValue())
					.intValue()), true);
			sb.append("end newId = " + String.valueOf(Double.valueOf(newcell.getNumericCellValue()).intValue())
					+ " ,result = " + result + "\n");
		}
		FileUtils.writeStringToFile(new File("d:/yaodian100.com/moveproduct_20110110.txt"), sb.toString());
	}

	// for (Product product : oldProducts) {
	// sb.append("product = ").append(product.getProductId()).append(",result = ").append(product.getMainCategoryID())
	// .append("\n");
	// }

	@Test
	public void updProductIsDelete() throws IOException, InvalidFormatException {
		File file = new File("D:/yaodian100.com/Book1.xlsx");
		InputStream inp = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(inp);
		Sheet sheet = wb.getSheetAt(0);
		Cell cell = null;
		StringBuffer data = new StringBuffer();
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			cell = row.getCell(0);
			// logger.info("cell:{}", row.getCell(0));
			Product entity = productService.get(cell.toString());
			entity.setIsDelete("Y");
			entity = productService.update(entity);
			// logger.info("entity:{} {}", entity.getProductId(), entity.getIsDelete());
			data.append("productId=").append(entity.getProductId()).append(",isDelete=").append(entity.getIsDelete()).append(
					"\n");

			// stringList.add(cell);
			// productService.update(entity)
		}
		FileUtils.writeStringToFile(new File("D:/yaodian100.com/n_product.txt"), data.toString());

		// String[] productIds = stringList.toArray(new String[0]);

		// daphneProductService.getAvailableDaphneProductMap();
	}

	@Test
	public void updProdCost() {
		remoteProductService.updateProductCost("00003378", new BigDecimal(62.0).setScale(1));
	}

	@Test
	// 转单商品更改为非转单状态
	public void testUpdateProductIsScm() throws Exception {
		// "00058902", "00057384", "00056756", "00056753",
		String[] prodIds = new String[] { "00056747" };
		Product product = null;
		for (String prodId : prodIds) {
			logger.info("prodIds:{}", prodId);
			product = productService.get(prodId);
			logger.info("before product:{} {}", product.getProductId(), product.getIsScm());
			product.setModifyUser("feeling.wang");
			product.setIsScm("N");
			product.setProductMemo("MIDEND BTS:509 转单商品更改为非转单状态");
			productService.save(product);
			logger.info("after product:{} {}", product.getProductId(), product.getIsScm());
		}
	}

	@Test
	public void testFeeling() {
		// CommonCriteria crit = new CommonCriteria();
		// crit.addEq("productId", "00029264");
		// List<ProductCategory> pcs = productService.getProductCategoryList(0, -1, crit, null);
		// Map pcsMap = ArrayUtils.toMap(pcs.toArray(new ProductCategory[0]));
		// logger.info("pcsMap:{}", pcsMap);
		List<Map<String, Object>> majors = jdbcTemplate
				.queryForList("select main_spec_id,is_cover from ec_specification_major where is_delete = 'N' and product_id = '00030461'");
		logger.info("majors:{}", majors);
	}
}